/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
*/

package com.ciwong.epaper.modules.cordva;


import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.modules.cordva.bean.ErrorBook;
import com.ciwong.epaper.modules.cordva.bean.Work;
import com.ciwong.epaper.modules.cordva.dao.CordvaDao;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.bean.EpaperInfo;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.epaper.bean.TempWorkAnswers;
import com.ciwong.epaper.modules.epaper.bean.VideoExplainWorkAnswers;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.dao.EpaperRequest;
import com.ciwong.epaper.modules.me.bean.CheckValidBean;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.epaper.modules.me.bean.ServiceDetail;
import com.ciwong.epaper.modules.viedoexplantion.util.ViedoJumpManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.MathExtend;
import com.ciwong.epaper.util.PayUtil;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.libs.widget.CWToast;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.widget.CWDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.ConfigXmlParser;
import org.apache.cordova.CordovaInterfaceImpl;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewImpl;
import org.apache.cordova.engine.SystemWebView;
import org.apache.cordova.engine.SystemWebViewClient;
import org.apache.cordova.engine.SystemWebViewEngine;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * created by young 2016/07/20
 */
public class CordovaWebViewTestActivity extends BaseActivity implements SystemWebViewClient.LoadCallback {

    public static final String TAG = "ciwong";

    private CordovaWebView cordovaWebView;
    public final ArrayBlockingQueue<String> onPageFinishedUrl = new ArrayBlockingQueue<String>(5);
    // public static final String START_URL = "file:///android_asset/errorBook/errorBook.html";
    public String START_URL = "file:///android_asset/err/app.html";
    private int type;
    private String pIndex = "1";
    private String psize = "10";
    private String htmlJson;
    private String Answer;
    public SystemWebView webView;
    //提交答案所需要信息
    private Module mModule;
    private String mDoWorkId;
    private String workId = "0";
    private static final int ERROR_BOOK = 1;
    private static final int ONLINE_PAPER = 2;
    private int position;
    private int totalTime = 0;

    private String mJsonResPath;
    private Work mWork;
    private String workjson;

    private String mTeacherComment;
    private String currenttitle;
    private String lasttitle;
    private long level = -1;
    private ViewGroup no_net_work;
    private Button try_again;
    //资源JSON
    private String result;


    private int mJumpSourcePage = -1;

    private int mServiceId;
    //用来标识数据是来自于本地还是来自于网络  表示是否已经从网络加载数据结束 必须要加载完网络数据后才能刷新页面
    private Boolean isFromNetData = false;
    //用于判断请求回来的错题本是否为空
    private Boolean isSizeNUll = false;
    private String letv = null;
    private int btn = 0;//0为显示掌握按钮

    private Context mContext;
    private ServiceDetail mServiceDetail;
    /**
     * 扫一扫数据所属的服务列表
     */
    private List<EpaperInfo.Server> mEpaperServerList;
    private EpaperInfo mEpaperInfo;
    private EApplication eApplication;
    private String classId;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //延时加载UI
            switch (msg.what) {
                case ERROR_BOOK:
                    //如果HTML为NULL 继续等待 1秒刷新一下
                    if (null == htmlJson) {
                        mHandler.sendEmptyMessageDelayed(ERROR_BOOK, 1000);//继续等待
                    } else {
                        //网络数据加载完成
                        if (isFromNetData) {
                            //错题为0
                            if (isSizeNUll) {
                                //android 4.4之后
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                    webView.evaluateJavascript("javascript:setData(" + null + ")", null);
                                } else {
                                    webView.loadUrl("javascript:setData(" + null + ")");
                                }

                            } else {//错题不为0
                                //android 4.4之后
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                    webView.evaluateJavascript("javascript:setData(" + htmlJson + ")", null);
                                } else {
                                    webView.loadUrl("javascript:setData(" + htmlJson + ")");
                                }

                            }
                        } else {
                            mHandler.sendEmptyMessageDelayed(ERROR_BOOK, 1000);//继续等待
                        }
                    }

                    break;
                case ONLINE_PAPER:
                    if (null != result) {
                        if (null != mDoWorkId) {
                            if (null == Answer) {
                                mHandler.sendEmptyMessageDelayed(ONLINE_PAPER, 1000);//Answer为空   继续等待
                            } else {
                                if (isFromNetData) {//加载网络完成
                                    loadHtmlData(result, Answer, workjson);
                                } else {
                                    mHandler.sendEmptyMessageDelayed(ONLINE_PAPER, 1000);//网络加载答案为完成  继续等待
                                }
                            }

                            //说明有答案
                            //先取本地答案
                            // Answer=ESystem.
                            //getVideoExplainAnswer(mDoWorkId, result,type);

                        } else {
                            //没有答案
                            loadHtmlData(result, null, workjson);
                        }
                    } else {
                        mHandler.sendEmptyMessageDelayed(ONLINE_PAPER, 1000);//获取资源json为空  等待
                    }

                   /* if (null != mJsonResPath) {
                       getResult(mJsonResPath);
                    }*/
                    break;
            }

        }
    };


    protected CordovaInterfaceImpl cordovaInterface = new CordovaInterfaceImpl(this) {
        @Override
        public Object onMessage(String id, Object data) {
            if ("onPageFinished".equals(id)) {
                onPageFinishedUrl.add((String) data);
            }
            return super.onMessage(id, data);
        }
    };


    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            //要做的事情
            totalTime++;
            handler.postDelayed(this, 1000);
        }
    };


    @Override
    protected int setView() {
        // stringByEvaluatingJavaScriptFromString
        return R.layout.htmlactivity;
    }

    @Override
    protected void findViews() {

    }

    @Override
    protected void initEvent() {
        webView = (SystemWebView) findViewById(R.id.cordovaWebView);
        no_net_work = findViewById(R.id.ll_no_net);
        try_again = (Button) findViewById(R.id.btn_retry);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void init() {

        //Set up the webview
        ConfigXmlParser parser = new ConfigXmlParser();
        parser.parse(this);
        cordovaWebView = new CordovaWebViewImpl(new SystemWebViewEngine(webView));
        cordovaWebView.init(this, cordovaInterface, parser.getPluginEntries(), parser.getPreferences());
        mContext = this;
        eApplication = (EApplication) getApplication();

        handler.postDelayed(runnable, 1000);//每一秒执行一次runnable
        //    webView.setLoadCallback(this);
        setGoBackListener(new GoBackListener() {
            @Override
            public void goBack() {
                onBackPressed();
            }
        });
        //错题本无网络条件下重试操作
        try_again.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webView.setVisibility(View.VISIBLE);
                no_net_work.setVisibility(View.GONE);
                //加载错题本
                getErrorBook();
                //mHandler.sendEmptyMessage(ERROR_BOOK);
            }
        });

//        //内存泄漏观察
//        RefWatcher refWatcher = EApplication.getRefWatcher(this);
//        refWatcher.watch(this);
    }

    @Override
    public void onBackPressed() {
        if ("举一反三".equals(getTitleText()) && type == EpaperConstant.H5_JUMP_TYPE_WRONG_QUESTION_BOOK) {
            webView.loadUrl("javascript:closeSample()");
            setTitleText("错题详情");
        } else if ("错题详情".equals(getTitleText())) {
            webView.loadUrl("javascript:closeWin()");
            setTitleText("错题本");
        } else if (level == 0) {
            webView.loadUrl("javascript:closeWin(" + lasttitle + ")");
        } else if (type == EpaperConstant.H5_JUMP_TYPE_WRONG_QUESTION_BOOK) {
            CordovaWebViewTestActivity.this.finish();
        } else if (mJumpSourcePage == EpaperConstant.H5_PAGE_TYPE_STUDY_RECORD || (Answer != null && Answer.length() > 0)) {
            //如果是做过的话就不用提示未完成学习了
            CordovaWebViewTestActivity.this.finish();
        } else {
            DialogUtil.showConfirmEndDialog(CordovaWebViewTestActivity.this);
        }
    }

    @Override
    protected void loadData() {
        Intent intent = getIntent();
        type = intent.getIntExtra(IntentFlag.INTENT_FLAG_TYPE, -1);
//        mAnswer = (Answer) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_ANSWER);
        mDoWorkId = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_DO_WORK_ID);
        lasttitle = intent.getStringExtra(IntentFlag.INTENT_FLAG_SERVICE_TITLE);
        lasttitle = "'" + lasttitle + "'";
        currenttitle = intent.getStringExtra(IntentFlag.INTENT_FLAG_SERVICE_TITLE);
        mJumpSourcePage = intent.getIntExtra(IntentFlag.INTENT_FLAG_H5_PAGE_TYPE_SOURCE, -1);
        classId = intent.getStringExtra(IntentFlag.INTENT_FLAG_CLASS_ID);
        //班级信息
        if (classId == null && EApplication.getInstance().getClazz() != null) {
            classId = String.valueOf(EApplication.getInstance().getClazz().getId());
        }
        if (null != mDoWorkId && mDoWorkId.equals("0")) {
            mDoWorkId = null;
        }
        mEpaperServerList = (List<EpaperInfo.Server>) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ_LIST);
        mEpaperInfo = (EpaperInfo) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_EPAPER_INFO);

        //服务id 用于作业提交，权限判断等
        mServiceId = intent.getIntExtra(IntentFlag.INTENT_FLAG_SERVICE_ID, -1);

        switch (type) {
            case EpaperConstant.H5_JUMP_TYPE_ONLINE_ANSWER://线上作答
                if (null == mDoWorkId) {
                    START_URL = "file://" + ESystem.getOnlinePaperPath() + File.separator + "paper.html";
                    // START_URL = "http://192.168.18.181/onlinePaper/onlinePaper/paper.html";

                } else {
                    START_URL = "file://" + ESystem.getOnlinePaperPath() + File.separator + "paperResult.html";
                    // START_URL = "http://192.168.18.181/onlinePaper/onlinePaper/paperResult.html";

                }
                setTitleText(currenttitle);
                break;
            case EpaperConstant.H5_JUMP_TYPE_VIDEO_EXPLAIN://视频讲解
                setTitleText(currenttitle);
                break;
//            case EpaperConstant.H5_JUMP_TYPE_WRONG_QUESTION_BOOK://错题本
//                START_URL = "file://" + ESystem.getErrorBookPath() + File.separator + "errorBook.html";
//                currenttitle = "错题本";
//                lasttitle = "'" + "错题本" + "'";
//                setTitleText(currenttitle);
//                //加载错题本
//                getErrorBook();
//                break;

        }


        //在此保存提交答案所需信息
        mModule = (Module) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
        workId = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_WORK_ID);
        if (TextUtils.isEmpty(workId)) {
            workId = "0";
        }
        position = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_POSITION, 0);
        mTeacherComment = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_TEACHER_COMMENT);


        //拼接WORK
        mWork = new Work();
        mWork.setBrandId(EApplication.BRAND_ID);
        if (null != mModule) {
            mWork.setcId(mModule.getModuleInfo().getcId());
            mWork.setModuleId(mModule.getModuleInfo().getModuleId());
        }
        if (mDoWorkId == null) {
            mWork.setDoWorkId("0");

        } else {
            mWork.setDoWorkId(mDoWorkId);
        }
        if (null == workId) {
            mWork.setTypeId(2);
        } else {
            mWork.setTypeId(1);
        }
        mWork.setUserId(CWSys.getSharedLong(BaseConstants.SHARE_PRE_CURR_LOGIN_USER, 0));
        workjson = new Gson().toJson(mWork);

        cordovaWebView.loadUrl(START_URL);
        initTeacherComment();


        //检查之前是否有未提交成功的作业
        checkSubmitFailedAnswer();
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        handler.removeCallbacks(runnable);
        if (webView != null)
            webView.destroy();
        if (cordovaWebView != null)
            cordovaWebView.getEngine().destroy();
        if (cordovaWebView != null)
            cordovaWebView.getPluginManager().onDestroy();
        super.onDestroy();
    }

    public CordovaWebView getCordovaWebView() {
        return cordovaWebView;
    }


    @Override
    public void onLoadOver() {
        switch (type) {
            case EpaperConstant.H5_JUMP_TYPE_ONLINE_ANSWER://线上作答
                // webView.loadUrl("javascript:callback(" + onlinePaper + ")");
            case EpaperConstant.H5_JUMP_TYPE_VIDEO_EXPLAIN://视频讲解
                mHandler.sendEmptyMessageDelayed(ONLINE_PAPER, 2000);
                break;
            case EpaperConstant.H5_JUMP_TYPE_WRONG_QUESTION_BOOK://错题本
                //分页查询错题本 第一页  20条数据
                //subjectId暂时传1
                mHandler.sendEmptyMessageDelayed(ERROR_BOOK, 1000);
                //mHandler.sendEmptyMessage(ERROR_BOOK);
                break;
        }

    }

    /**
     * 获取错题本接口  获取本地
     */
    public void getErrorBook() {
        //去本地数据错题
        SerializableManager.getInstance().deSerialize(EApplication.BRAND_ID + "", new BaseExtCallBack(mContext, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                //判断错题本网络状态，无网络提示用户
                super.failed(errorCode, data);
                showNetErrorWork();
                getErrorBookfromNet();
            }

            @Override
            public void failed(Object data) {
                //判断错题本网络状态，无网络提示用户
                showNetErrorWork();
                getErrorBookfromNet();
            }

            @Override
            public void success(Object data) {
                ErrorBook errorBook = (ErrorBook) data;
                htmlJson = new Gson().toJson(errorBook);
                CWLog.d("errBooksuccess", htmlJson);
                if (htmlJson == null) {
                    //判断错题本网络状态，无网络提示用户
                    showNetErrorWork();
                }
                getErrorBookfromNet();
            }
        }, true);


    }

    //获取网络上错题本资源
    private void getErrorBookfromNet() {
        CordvaDao.getInstance().selectErrorBook(EApplication.BRAND_ID + "", pIndex, psize, "1", new BaseExtCallBack(mContext, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                isFromNetData = true;
                //加载本地数据
                // webView.evaluateJavascript("javascript:setData(" + htmlJson + ")",null);
                //htmlJson=null;
            }

            @Override
            public void failed(Object data) {
                isFromNetData = true;
                //加载本地数据
                //webView.evaluateJavascript("javascript:setData(" + htmlJson + ")",null);
                //htmlJson=null;
            }

            @Override
            public void success(Object data) {

                isFromNetData = true;
                ErrorBook errorBook = (ErrorBook) data;
                htmlJson = new Gson().toJson(errorBook);
                if (errorBook == null) {
                    isSizeNUll = true;
                }
                if (errorBook != null && htmlJson != null) {
                    //webView.evaluateJavascript("javascript:setData(" + htmlJson + ")",null);
                    SerializableManager.getInstance().serialize(EApplication.BRAND_ID + "", errorBook, true);
                } else {

                    //webView.loadUrl("javascript:setData(" + null + ")");
                    //webView.evaluateJavascript("javascript:setData(" + null + ")",null);
                }
            }
        });
    }


    @Override
    public void onBackFinish() {
    }

    String score = "0.0";

    public void onEventMainThread(SubmitEvent submitEvent) {
        final String id = submitEvent.getId();
        final String callbackId = submitEvent.getCallbackId();
        if ("AddErrorBook".equals(id)) {
            try {
                if (null != submitEvent.getJson()) {
                    JSONObject jsonObject = new JSONObject(submitEvent.getJson());
                    String resourceName = jsonObject.getString("resourceName");
                    int subjectId = jsonObject.getInt("subjectId");
                    String versionId = jsonObject.getString("versionId");
                    int moduleId = jsonObject.getInt("moduleId");
                    String cId = jsonObject.getString("cId");
                    String packageId = jsonObject.getString("packageId");
                    String doWorkId = jsonObject.getString("doWorkId");
                    int typeId = jsonObject.getInt("typeId");
                    //添加错题 学科暂时先传1
                    if (!NetworkUtils.isOnline()) {
                        sendCallBack(callbackId, 0);
                        CWToast.makeText(CordovaWebViewTestActivity.this, R.string.pull_to_refresh_network_error, Toast.LENGTH_LONG, true)
                                .setToastType(CWToast.TOAST_TYPE_ALERT).show();
                    }
                    addErrorBook(EApplication.BRAND_ID + "", doWorkId, typeId + "", packageId, cId, moduleId + "", versionId, resourceName, "1", callbackId);
                }

            } catch (Exception e) {
                e.getStackTrace();
            }
        } else if ("Submit".equals(id)) {
            //提交作业
            //submit(submitEvent.getJson());
            //作业做完前提下

            score = submitEvent.getScore();
            //保留2位小数
            score = PayUtil.radixPoint(Double.valueOf(score), 2);
            while (score.endsWith("0") || score.endsWith(".")) {
                if (score.endsWith("0") && (score.length() - 2) >= 0) {
                    score = score.substring(0, score.length() - 1);
                } else if (score.endsWith(".") && (score.length() - 2) >= 0) {
                    score = score.substring(0, score.length() - 1);
                    break;
                }
            }

            String remainNum = submitEvent.getRemainNum();

            if (null != remainNum && remainNum.equals("0")) {

                saveAnswer(submitEvent.getJson());//在本地保存一份答案
            } else {
                String tips = "您还有" + remainNum + "道题目未完成，确定交卷吗？";
                showConfirmCommitDialog(this, tips, submitEvent, score);
            }


        } else if ("SetTitle".equals(id)) {
            try {
                String arg = submitEvent.getJson();
                JSONObject jsonObject = new JSONObject(arg);
                if (jsonObject.has("title")) {
                    currenttitle = jsonObject.getString("title");
                }
                if (jsonObject.has("level")) {
                    level = jsonObject.getLong("level");
                }
                //改变Title 方法
                setTitleText(currenttitle);
            } catch (Exception e) {
                e.getStackTrace();
            }

        } else if ("OpenVideo".equals(id)) {
            //打开视频事件处理

            Log.d(TAG, "######OpenVideo#########");

            openVideo(submitEvent, callbackId);
        }

    }

    private void openVideo(SubmitEvent submitEvent, final String callbackId) {
        String productId = null;//判断视频播放权限所需参数
        String quesId = null;//判断视频播放权限所需参数
        String letvId = null;//判断视频播放权限所需参数
        try {
            String arg = submitEvent.getJson();
            JSONObject jsonObject = new JSONObject(arg);
            if (jsonObject.has("productId")) {
                productId = jsonObject.getString("productId");
            }
            if (jsonObject.has("letv")) {
                letvId = jsonObject.getString("letv");
            }
            if (jsonObject.has("quesId")) {
                quesId = jsonObject.getString("quesId");
            }
            if (jsonObject.has("queNum")) {
                jsonObject.getString("queNum");
            }
            if (jsonObject.has("videoTitle")) {
                jsonObject.getString("videoTitle");
            }


            if (NetworkUtils.isOnline()) {
                IsCanOpenVideo(quesId, letvId, productId, callbackId);
            } else {
                //无网络提示用户
                Toast.makeText(mContext, R.string.connect_disable2, Toast.LENGTH_LONG).show();
            }


        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    /**
     * @param quesId
     * @param letvId
     * @param productId
     */
    private void IsCanOpenVideo(String quesId, String letvId, String productId, final String callbackId) {

        String serviceId = null;
        //扫一扫进来木有service id
        if (mServiceId > 0) {
            serviceId = "" + mServiceId;
        }
    }


    //获取本地答案数据
    private void getVideoExplainAnswer(String doWorkId, final String json, int requestType) {
        //取本地数据
        SerializableManager.getInstance().deSerialize(doWorkId, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                //请求网络答案数据
                getVideoExplainAnswerfromNet(mDoWorkId, json, type);
            }

            @Override
            public void failed(Object data) {
                //请求网络答案数据
                getVideoExplainAnswerfromNet(mDoWorkId, json, type);
            }

            @Override
            public void success(Object data) {
                if (type == EpaperConstant.H5_JUMP_TYPE_ONLINE_ANSWER) {
                    List<TempWorkAnswers> list = (List<TempWorkAnswers>) data;
                    if (null != list) {
                        Answer = new Gson().toJson(list);
                    }

                } else {
                    List<VideoExplainWorkAnswers> list = (List<VideoExplainWorkAnswers>) data;
                    if (null != list) {
                        Answer = new Gson().toJson(list);
                    }
                }
                //请求网络答案数据
                getVideoExplainAnswerfromNet(mDoWorkId, json, type);
            }
        }, true);

    }

    //请求网络答案数据
    private void getVideoExplainAnswerfromNet(final String doWorkId, final String json, int requestType) {
        //判断是否有答案，有就传人h5 处理
        EpaperDao.getInstance().getVideoExplainAnswer(doWorkId, requestType, new BaseExtCallBack(mContext, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


            @Override
            public void success(Object data) {
                isFromNetData = true;
                if (type == EpaperConstant.H5_JUMP_TYPE_ONLINE_ANSWER) {

                    List<TempWorkAnswers> list = (List<TempWorkAnswers>) data;
                    if (null != list) {
                        //答案保存在本地
                        SerializableManager.getInstance().serialize(doWorkId, (Serializable) list, true);
                        Answer = new Gson().toJson(list);
                    }

                } else {
                    List<VideoExplainWorkAnswers> list = (List<VideoExplainWorkAnswers>) data;
                    if (null != list) {
                        //答案保存在本地
                        SerializableManager.getInstance().serialize(doWorkId, (Serializable) list, true);
                        Answer = new Gson().toJson(list);
                    }
                }

                //转换成answer,
                Log.d("ciwong", "#########success###########" + data.toString());
                //loadHtmlData(json, Answer, workjson);

            }

            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                isFromNetData = true;
                //loadHtmlData(json, Answer, workjson);
            }

            @Override
            public void failed(Object data) {
                super.failed(data);
                isFromNetData = true;
                //loadHtmlData(json, Answer, workjson);
            }
        });
    }

    //加载H5数据
    private void loadHtmlData(String json, String answer, String work) {
        try {
            switch (type) {
                case EpaperConstant.H5_JUMP_TYPE_ONLINE_ANSWER://线上作答
                    if (null != answer) {
                        //android 5.0之后
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            webView.evaluateJavascript("javascript:callback(" + json + "," + answer + ")", null);
                        } else {
                            webView.loadUrl("javascript:callback(" + json + "," + answer + ")");
                        }
                        //webView.loadUrl("javascript:callback(" + json + "," + answer + ")");

                    } else {
                        //android 5.0之后
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            webView.evaluateJavascript("javascript:callback(" + json + ")", null);
                        } else {
                            webView.loadUrl("javascript:callback(" + json + ")");
                        }
                        //webView.loadUrl("javascript:callback(" + json + ")");

                    }
                    break;
                case EpaperConstant.H5_JUMP_TYPE_VIDEO_EXPLAIN://视频讲解
                    if (null != answer) {
                        //android 5.0之后
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            webView.evaluateJavascript("javascript:setData(" + json + "," + work + "," + answer + ")", null);
                        } else {
                            webView.loadUrl("javascript:setData(" + json + "," + work + "," + answer + ")");
                        }
                        //webView.loadUrl("javascript:setData(" + json + "," + work + "," + answer + ")");

                    } else {
                        //android 5.0之后
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            webView.evaluateJavascript("javascript:setData(" + json + "," + work + ")", null);
                        } else {
                            webView.loadUrl("javascript:setData(" + json + "," + work + ")");
                        }
                        //webView.loadUrl("javascript:setData(" + json + "," + work + ")");

                    }
                    break;
            }
        } catch (IllegalStateException e) {

        } catch (NullPointerException e) {

        }
    }

    //发送回调
    private void sendCallBack(String callbackId, int msg) {
        if (!callbackId.isEmpty()) {
            CallbackContext callbackContext = new CallbackContext(callbackId, cordovaWebView);
            callbackContext.success(msg);
        }
    }

    /**
     * 增加错题本
     */

    private void addErrorBook(String brandId, String doWorkId, String typeId, String packageId, String cId, String moduleId, String versionId, String resourceName, String subjectId, final String callbackId) {

        CordvaDao.getInstance().addErrorBook(brandId, doWorkId, typeId, packageId, cId, moduleId, versionId, resourceName, subjectId, new BaseExtCallBack(mContext, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                sendCallBack(callbackId, 0);
            }


            @Override
            public void failed(Object data) {
                sendCallBack(callbackId, 0);
            }

            @Override
            public void success(Object data) {
                sendCallBack(callbackId, 1);
            }
        });
    }


    private void initTeacherComment() {
        {
            if (null != mTeacherComment && mTeacherComment.length() > 0) {
                setRightBtnBG(R.mipmap.icon_teacher_comment);
                setRightBtnEnable(true);
                setRightBtnListener(new ViewOnClickListener() {
                    @Override
                    public void avertRepeatOnClick(View v) {
                        DialogUtil.showCommentDialog(CordovaWebViewTestActivity.this, mTeacherComment);
                    }
                });
            }
        }
    }

    /**
     * 未完成作业提交提醒窗口
     */
    public void showConfirmCommitDialog(final Activity context, final String tips, final SubmitEvent submitEvent, final String s) {
        CWDialog dialog = new CWDialog(context);
        dialog.setMessage(tips);
        dialog.setPositiveButton(android.R.string.cancel, null)
                .setNegativeButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
//                                ViedoJumpManager.jumpToResultActivity(R.string.go_back, context, EpaperConstant.REQUEST_CODE_VIDEO_EXPLAIN_ONLINE_ANSWER_RESUTL, type, workId, mDownLoadInfo, mModule, position, mDoWorkId, submitEvent.getJson(), totalTime, s, mJumpSourcePage, mServiceId, classId);
                                saveAnswer(submitEvent.getJson());

                            }
                        })
                .show();
    }


    /**
     * 无网络环境下的时候，显示提醒页面
     */
    private void showNetErrorWork() {
        if (!NetworkUtils.isOnline() && type == EpaperConstant.H5_JUMP_TYPE_WRONG_QUESTION_BOOK) {
            webView.setVisibility(View.GONE);
            no_net_work.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 获取网页展示内容
     *
     * @param path
     */
    private void getResult(final String path) {
        EpaperDao.getInstance().getResource(path, new BaseExtCallBack(mContext, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void success(final Object data) {
                if (isFinishing()) {
                    return;
                }
                result = ESystem.formatJsonStr(data.toString());
               /* if (null != result) {
                    if (null != mDoWorkId) {
                        //说明有答案
                        //先取本地答案
                       // Answer=ESystem.
                        getVideoExplainAnswer(mDoWorkId, result,type);

                    } else {

                        loadHtmlData(result, null, workjson);
                    }
                }*/
                if (null != mDoWorkId) {
                    //说明有答案
                    //先取本地答案
                    // Answer=ESystem.
                    getVideoExplainAnswer(mDoWorkId, result, type);
                }
                Log.d(TAG, "########result############：" + result);
            }

            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
            }

            @Override
            public void failed(Object data) {
                showToastError((int) data);
            }
        });
    }


    private void checkSubmitFailedAnswer() {
        //将本页面的数据封装成answer，
        Answer answer = new Answer();
        answer.setWorkId(workId);
        answer.setWorkLong(totalTime);

        answer.setClassId(classId);
        answer.setPackageId(getPackageName());
        EApplication application = (EApplication) getBaseApplication();
        UserInfoBase userInfo = application.getUserInfoBase();
        answer.setUserName(userInfo.getRealName());
        answer.setWorkType(mServiceId);

        SerializableManager.getInstance().deSerialize("FailedAnswer" + position + mModule.getResourceList().get(position).getVersionId() + workId, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {

            }

            @Override
            public void failed(Object data) {

            }

            @Override
            public void success(Object data) {
                if (data != null) {
                    tempAnswer = (com.ciwong.epaper.modules.epaper.bean.Answer) data;
                    if (TextUtils.isEmpty(workId)) {
                        ViedoJumpManager.jumpToResultActivityAgain(R.string.go_back, CordovaWebViewTestActivity.this, RequestCode.HomeWorkFragmentResquestCode.REQ_ONLINE_ANSWER, type, workId,
                                mModule, position, mDoWorkId, true, totalTime, score, mJumpSourcePage, mServiceId, classId, tempAnswer);
                    } else if (!TextUtils.isEmpty(tempAnswer.getWorkId()) && tempAnswer.getWorkId().equals(workId)) {
                        ViedoJumpManager.jumpToResultActivityAgain(R.string.go_back, CordovaWebViewTestActivity.this, RequestCode.HomeWorkFragmentResquestCode.REQ_ONLINE_ANSWER, type, workId,
                                mModule, position, mDoWorkId, true, totalTime, score, mJumpSourcePage, mServiceId, classId, tempAnswer);
                    }
                }
                super.success(data);
            }

            @Override
            public void success() {
                super.success();
            }
        });
    }

    Answer tempAnswer;
    private UserInfoBase userInfo;

    private void saveAnswer(String jsonSource) {
        //根据json 拼answer
        Gson gson = new Gson();


        tempAnswer = new Answer();
        EApplication application = (EApplication) getBaseApplication();
        Clazz clazz = application.getClazz();
        userInfo = application.getUserInfoBase();
        if (mModule != null && null != userInfo && null != jsonSource) {
            if (null == workId || workId.equals("")) {
                workId = "0";
            }
            tempAnswer.setWorkId(workId);
            tempAnswer.setWorkLong(totalTime);
            if (clazz == null || TextUtils.isEmpty(classId)) {
                classId = "0";
            }
            tempAnswer.setClassId(classId);
            tempAnswer.setUserName(userInfo.getRealName());
            tempAnswer.setWorkType(mServiceId);
            Type responseType;
            List<TempWorkAnswers> onWorkAnswersList = new ArrayList<>();
            List<VideoExplainWorkAnswers> userAnswerseList = new ArrayList<>();
            if (type == EpaperConstant.H5_JUMP_TYPE_ONLINE_ANSWER) {

                responseType = new TypeToken<List<TempWorkAnswers>>() {
                }.getType();
                onWorkAnswersList = gson.fromJson(jsonSource, responseType);

                if (null != score && Float.valueOf(score) >= 0) {
                    tempAnswer.setActualScore(Float.valueOf(score));
                } else {
                    tempAnswer.setActualScore(getOnlineScore(jsonSource));
                }

//                showCricleProgress("作业正在提交...");
//                EpaperDao.getInstance().packSubmitAnswer(getUserInfoBase().getUserId(), uuid, tempAnswer, onWorkAnswersList, responseType, mDownLoadInfo, mModule, position, true, ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN, null, new SubmitBaseCallBack(true));

            } else {

                responseType = new TypeToken<List<VideoExplainWorkAnswers>>() {
                }.getType();
                userAnswerseList = gson.fromJson(jsonSource, responseType);
                tempAnswer.setActualScore(getScoreOrMasterRate(jsonSource));
//                EpaperDao.getInstance().packSubmitAnswer(getUserInfoBase().getUserId(), uuid, tempAnswer, userAnswerseList, responseType, mDownLoadInfo, mModule, position, true, ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN, null, new SubmitBaseCallBack(true));
            }
            tempAnswer.setJsonVersion(EConstants.JSON_VERSION);
            tempAnswer.setUserAnswer(ESystem.USER_ANSWER);
            tempAnswer.setCreateTime(System.currentTimeMillis());
            tempAnswer.setBrandId(EApplication.BRAND_ID);
            String refAnswerPath = null;
            int moduleId;

            if (mModule != null) {
                ModuleContent moduleContent = mModule.getResourceList().get(position);
                moduleId = mModule.getModuleInfo().getModuleId();

                if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM || moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN || moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_ONLINE_ANSWER) {

                    if (null != moduleContent.getRefAnswerFile() && moduleContent.getRefAnswerFile().length() > 0) {
                        refAnswerPath = ESystem.getPackagesPath()
                                + File.separator
                                + moduleContent.getRefAnswerFile();
                        tempAnswer.setRefAnswer(ESystem.REF_ANSWER);

                    } else {
                        //由于视频讲解跟在线作答资源没有refanser ,必须自己拷贝
                        String packageJsonPath = ESystem.getPackagesJsonPath(mModule.getResourceList().get(position).getResourceFile());
                        refAnswerPath = packageJsonPath;
                        tempAnswer.setRefAnswer(ESystem.REF_ANSWER);
                    }

                }

                tempAnswer.setResourceName(moduleContent.getResourceName());
                tempAnswer.setVersionId(moduleContent.getVersionId());
                tempAnswer.setParentVersionId(moduleContent.getParentVersionId());
                tempAnswer.setModuleId(moduleId);
                tempAnswer.setResourceType(moduleContent.getResourceType());

            }
            try {
                // 生成main.json
                FileUtils.save(gson.toJson(tempAnswer), ESystem.getAnswersMainPath(uuid));
                // 生成refAnswers.json
                if (refAnswerPath != null) {
                    File refFile = new File(ESystem.getAnswersRefAnswerPath(uuid));
                    if (!refFile.exists()) {
                        refFile.createNewFile();
                    }
                    FileUtils.copyFile(refAnswerPath, ESystem.getAnswersRefAnswerPath(uuid));
                }

                // 生成userAnswer.json
                String userAnswerJson = responseType == null
                        ? gson.toJson(onWorkAnswersList)
                        : gson.toJson(onWorkAnswersList, responseType);


                FileUtils.save(userAnswerJson, ESystem.getAnswersUserAnswerPath(uuid));


                if (!TextUtils.isEmpty(userAnswerJson)) {

                    tempAnswer.setWorkAnswers(userAnswerJson);

                }
                // 将记录保存在本地
                String zipPath = EpaperDao.getInstance().generateZipFile(uuid);
                //将答案记录到本地
                SerializableManager.getInstance().serialize("FailedAnswer" + position + mModule.getResourceList().get(position).getVersionId() + workId, tempAnswer);
                tempAnswer.setDoWorkLocalPath(zipPath);
                if (TextUtils.isEmpty(workId)) {
                    workId = "0";
                }
                ViedoJumpManager.jumpToResultActivityAgain(R.string.go_back, this, RequestCode.HomeWorkFragmentResquestCode.REQ_ONLINE_ANSWER, type, workId,
                        mModule, position, mDoWorkId, false, totalTime, score, mJumpSourcePage, mServiceId, classId, tempAnswer);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private String uuid = UUID.randomUUID().toString();
    private Gson mGson = new Gson();

    private float getOnlineScore(String jsonSource) {
        List<TempWorkAnswers> onWorkAnswersList = new ArrayList<>();
        Type responseType;
        responseType = new TypeToken<List<TempWorkAnswers>>() {
        }.getType();
        onWorkAnswersList = mGson.fromJson(jsonSource, responseType);
        float score = 0f;
        if (onWorkAnswersList != null && onWorkAnswersList.size() > 0) {
            for (int i = 0; i < onWorkAnswersList.size(); i++) {
                TempWorkAnswers onlineAnswerInfoWorkAnswers = onWorkAnswersList.get(i);
                score = score + onlineAnswerInfoWorkAnswers.getScore();
            }
        }
        return score;
    }

    /**
     * 客户端自己计算获取掌握率
     *
     * @return
     */
    private float getScoreOrMasterRate(String jsonSource) {
        float masterRate = 0f;// 掌握率
        int masteredStatusYes = 0;
        int masteredStatusNot = 0;
        int masteredStatusNotConfirm = 0;
        List<VideoExplainWorkAnswers> userAnswerseList = new ArrayList<>();
        Type responseType;
        responseType = new TypeToken<List<VideoExplainWorkAnswers>>() {
        }.getType();
        userAnswerseList = mGson.fromJson(jsonSource, responseType);

        if (mModule.getModuleInfo().getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN) {
            if (userAnswerseList != null && userAnswerseList.size() > 0) {
                for (int i = 0; i < userAnswerseList.size(); i++) {
                    VideoExplainWorkAnswers videoExplainWorkAnswers = userAnswerseList.get(i);
                    {
                        if (mModule.getModuleInfo().getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN) {
                            // 掌握率
                            if (videoExplainWorkAnswers.getMasteredStatus() == 0) {
                                masteredStatusNotConfirm++;
                            } else if (videoExplainWorkAnswers.getMasteredStatus() == 1) {
                                masteredStatusYes++;
                            } else if (videoExplainWorkAnswers.getMasteredStatus() == 2) {
                                masteredStatusNotConfirm++;
                            }
                        }
                    }
                }
            }
        }

        int totalCount = masteredStatusYes + masteredStatusNot + masteredStatusNotConfirm;
        if (totalCount > 0) {
            masterRate = (float) MathExtend.divide(masteredStatusYes, masteredStatusYes + masteredStatusNot + masteredStatusNotConfirm, 2);
        }
        return masterRate * 100;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case EpaperConstant.REQUEST_CODE_GET_VIDEO_MASTER_STATE:
                if (data != null) {
                    String callbackid = data.getStringExtra(IntentFlag.INTENT_FLAG_ID);
                    // String msg=data.getStringExtra(IntentFlag.INTENT_FLAG_SMS);
                    if (!callbackid.isEmpty()) {
                        CallbackContext callbackContext = new CallbackContext(callbackid, cordovaWebView);
                    }
                }

                break;
            case EpaperConstant.REQUEST_CODE_VIDEO_EXPLAIN_ONLINE_ANSWER_RESUTL:
                if (resultCode == RESULT_OK) {
                    setResult(RESULT_OK);
                    finish();
                }
                break;
            case RequestCode.HomeWorkFragmentResquestCode.REQ_ONLINE_ANSWER:
                if (resultCode == RESULT_OK) {
                    setResult(RESULT_OK);

                }
                finish();
                break;
        }

    }
}
